//layui模块的定义
;layui.define(['jquery', 'myFaApi','upload','layer','myInit', 'myUtil'], function(exports) {
	var $ = layui.jquery, myFaApi = layui.myFaApi, upload = layui.upload, layer = layui.layer, myUtil = layui.myUtil;
	//上传资料
	var qiniuUploadUrl = "http://up.qiniu.com";
	/**
	 * 文件各类型后缀
	 */
	var img_extensions = "jpg,gif,png,jpeg,JPG,GIF,PNG,JPEG";
	var video_extensions = "mp4,flv,avi,mp3,rm,mov,MP4,FLV,AVI,MP3,RM,MOV";
	var word_extensions = "docx,doc";
	var excel_extensions = "xlsx,xls";
	var loadIndex;
	var uploading = false;

	var qiniu = {};
	/**
	 * 获取七牛token
	 * obj:file dom对象
	 * img:是否是图片
	 * callback
	 */
	qiniu.getToken = function(obj, img, callback) {
		if(!obj) {
			return;
		}
		img = (img == false ? false : true);
		edit = callback ? true : false;
		var length;
   		if(myUtil.isIE()) {
   			var filePath = obj.value; 
   			var fileSystem = new ActiveXObject("Scripting.FileSystemObject");
            var localFile = fileSystem.GetFile(filePath);
            if(!localFile) {
            	return;
            }
            length = localFile.Size;    // 文件大小，单位：b
   		} else {
   			if(!obj.files || obj.files.length == 0) {
   				return;
   			}
   			length = obj.files[0].size;
   		}
   		
   		var size = length / 1024 / 1024;
        if (img && size > 3) {
            layer.msg('文件大小不能超过3M');
            return;
        } else if(size > 100){
        	layer.msg('文件大小不能超过100M');
            return;
        }
        if(uploading) {
        	return;
        }
        uploading = true;
		$.myAjax({
			data:{},
			url:myFaApi.qiniuToken,
			success:function(result) {
				var token = result.content.token;
				var gateway = result.content.gateway;
				loadIndex = layer.load();
				qiniuUpload(obj.files[0], token, gateway, function(fileKey) {
					uploading = false;
					if(callback) {
						callback(fileKey);
					} else {
						var $parent = $(obj).parent('div');
						if(img){
							$parent.find('img').attr('src', fileKey);
						}else{
							$parent.find('img').attr('src', 'http://sharetest.diepusoft.com/e90f3b2c9034127e600574bc887717d4.png');
						}
						$parent.find('input.img-url').val(fileKey);
					}
				});
			}
		});
	}
	
	/**
	 * 七牛上传
	 * @param {Object} file
	 */
	qiniuUpload = function(file, token, gateway, callback) {
		if(!file) {
			layer.msg('请选择文件',{icon:6})
			layer.close(loadIndex);
			return;
		}
    	var xhr;
        if(window.XMLHttpRequest){  
        	xhr = new XMLHttpRequest();  
        } else if(window.ActiveXObject){  
            var activeName=["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];  
            for(var i=0;i<activeName.length;i++){  
                try{  
                	xhr=new ActiveXObject(activeName[i]);  
                    break;  
                }catch(e){  
                 	if(console){
                 		console.info('ActiveXObject 创建失败');
                 	}            
                }  
            }  
        }
    	xhr.open('POST', qiniuUploadUrl, true);
   		var formData = new FormData();
   		var fileName = file.name;
   		var fileKey = getFileKey(fileName);
	    formData.append('key', fileKey);
	    formData.append('token', token);
	    formData.append('file', file);
	    xhr.onreadystatechange = function (response) {
	        if (xhr.readyState == 4 && xhr.status == 200) {
	        	layer.close(loadIndex);
	        	layer.msg('上传成功', {icon: 5});
	        	if(callback) {
	        		callback(gateway + fileKey);
	        	}
	        } else if (xhr.status != 200 && xhr.responseText) {
	        	layer.close(loadIndex);
	        	layer.msg('上传失败', {icon: 6});
	        }
	    };
	    xhr.send(formData);
	}
	
	/**
	 * 根据后缀分析文件类型
	 * fileName 文件名/文件后缀
	 */
	function parseTypeAttachment(fileName){
		if(fileName && fileName != '') {
			var periodInd = fileName.lastIndexOf('.');
			var extension = '';
			if(periodInd >= 0) {
				extension = fileName.substring(periodInd + 1);
			} else {
				extension = fileName;
			}
			if(video_extensions.indexOf(extension) >= 0) {
				return 'video';
			} else if(img_extensions.indexOf(extension) >= 0) {
				return 'img';
			} else if(word_extensions.indexOf(extension) >= 0) {
				return 'word';
			} else if(excel_extensions.indexOf(extension) >= 0) {
				return 'excel';
			}
		}
		return 'other';
	}
	
	function getFileKey(fileName) {
         //文件后缀
	    var subfixIndex = fileName.lastIndexOf(".");
	    if(subfixIndex <= 0) {
	    	layer.msg("已取消或文件格式错误", {icon: 5});
	    	return;
	    }
	    subfix = fileName.substring(subfixIndex);
        return myUtil.guid() + subfix;
	}
	
	
	exports('qiniu', qiniu);
});
